import {
  getLivesAndCourses,
  getInformationDetail,
  getRelevantArticle
} from '@/api/information_detail'
import { getSearchWords } from '@/api/information_home'
import tool from '@/utils/tool'
export default {
  namespaced: true,
  state: () => ({
    //文章详情页
    articleData: {},
    // 大家都在搜
    keyWords: [],
    // 课程和直播
    coursesAndLives: {}
  }),
  mutations: {
    // 设置文章详情
    setArticleData(state, data) {
      // state.articleData = data
      state.articleData = tool.encodeString(data)
    },
    // 设置相关文章和可能感兴趣
    setRelevantData(state, data) {
      state.relevantArticles = data.article
      state.lateHots = data.search
    },
    // 设置大家都在搜
    setKeyWords(state, data) {
      // state.keyWords = data
      state.keyWords = tool.encodeString(data)
    },
    // 设置课程和直播
    setCouraseAndLives(state, data) {
      state.coursesAndLives = tool.encodeString(data)
    }
  },
  actions: {
    // 页面初始化
    async init({ commit, dispatch, state }, { params, context }) {
      await dispatch('getArticleData', { params, context })
      let obj = tool.decodeString(state.articleData) || {}
      // let { zl_profession_id: profession_id } = state.articleData.detail || {
      //   zl_profession_id: 4
      // }
      let { zl_profession_id: profession_id } = obj.detail || {
        zl_profession_id: 4
      }
      await Promise.all([
        dispatch('getKeyWords', { profession_id }),
        dispatch('getLivesAndCourses', { profession_id })
      ])
      return true
    },
    // 获取文章详情、相关文章
    async getArticleData({ commit }, { params, context }) {
      let { isSpider } = context
      if (isSpider === true) {
        params.isServiceCache = false
      }
      let res = await getInformationDetail(params).catch(err => {
        return { data: {} }
      })
      if (+res.errcode === 0) {
        if (res.data) {
          // 处理文章中的相关关键字
          let { detail = {}, key_words_link = [] } = res.data
          let content = detail.content || ''
          // 处理文章中关键词已经被添加a标签
          detail.content = handleContentAtag(content, key_words_link)
          function handleContentAtag(replaceCont, keywordsLink) {
            // 这里处理 关键词只出现一次,添加isUse 标识是否使用，1是使用
            if (Array.isArray(keywordsLink)) {
              keywordsLink.forEach(keyWordsItem => {
                if (typeof keyWordsItem === 'object') {
                  keyWordsItem.isUse = 0
                }
              })
            }
            // 区分a标签和img标签中是否有关键词，有关键词也不特殊处理
            var matchHref = new RegExp(
              `<a(.*?)href="(.*?)"(.*?)>(.*?)</a>|<img(.*?)src="(.*?)"/>`,
              'ig'
            )
            var aArr = replaceCont.match(matchHref) || []
            var strArr = []
            strArr.push(replaceCont)
            // 将字符串已每个a标签拆分
            for (var strIndex = 0; strIndex < aArr.length; strIndex++) {
              var arr = []
              strArr.forEach(strItem => {
                var arr1 = strItem.split(aArr[strIndex])
                if (arr1.length == 0) return
                arr1.forEach((strItem1, strItem1Index) => {
                  arr.push(strItem1)
                  if (strItem1Index != arr1.length - 1) {
                    arr.push(aArr[strIndex])
                  }
                })
              })
              strArr = arr
            }
            strArr = strArr.map(strItem => {
              var temporaryStr = strItem
              // 不对a、img标签处理
              if (
                temporaryStr.indexOf('</a>') !== -1 ||
                temporaryStr.indexOf('<img') !== -1
              )
                return temporaryStr
              keywordsLink.forEach(keyItem => {
                if (
                  temporaryStr.indexOf(keyItem.word) !== -1 &&
                  keyItem.isUse === 0
                ) {
                  // 标识改为1 ，下次不在使用
                  keyItem.isUse = 1
                  var re_cont = `<a href="${keyItem.url}" target="_blank" style="color:#3480ff;text-decoration:none;">${keyItem.word}</a>`
                  temporaryStr = temporaryStr.replace(keyItem.word, re_cont)
                }
              })
              return temporaryStr
            })
            return strArr.join('')
          }
          commit('setArticleData', res.data)
          res.data.detail &&
            commit(
              'setMeta',
              { data: res.data.detail, context },
              { root: true }
            )
        }
      } else {
        throw { code: 404 }
      }
    },
    // 获取热门推荐和大家都在搜
    // async getRelevantArticle({ commit }, params) {
    //   let res = await getRelevantArticle(params).catch(err => {
    //     return { data: {} }
    //   })
    //   res && res.data && commit('setRelevantData', res.data)
    // },
    // 获取大家都在搜
    async getKeyWords({ commit }, params) {
      let res = await getSearchWords(params).catch(err => {
        return { data: {} }
      })
      res && res.data && commit('setKeyWords', res.data)
    },
    // 获取课程和直播
    async getLivesAndCourses({ commit }, params) {
      let res = await getLivesAndCourses(params).catch(err => {
        return { data: {} }
      })
      res && res.data && commit('setCouraseAndLives', res.data)
    }
  },
  getters: {}
}
